package com.kun.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.kun.annotation.LoginUser;
import com.kun.entity.SysMenu;
import com.kun.entity.SysUser;
import com.kun.service.SysMenuService;
import com.kun.util.ResponseResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author kun.li
 */
@RestController
@RequestMapping("menu")
@Tag(name = "菜单管理")
public class MenuController {
    @Resource
    private SysMenuService sysMenuService;


    @Operation(summary = "根据租户ID和用户Id获取所有的前端路由")
    @GetMapping("getUserRoutes/{tenantId}/{userId}")
    public ResponseResult<Map<String, Object>> getMenuList(@PathVariable("tenantId") String tenantId, @PathVariable("userId") String userId) {
        return ResponseResult.success(sysMenuService.getRoute(tenantId, userId));

    }

    @Operation(summary = "根据角色获取对应的所有权限")
    @GetMapping("getMenuListByRoelId/{roleId}")
    public ResponseResult<List<String>> getMenuListByRoelId(@PathVariable String roleId) {
        List<SysMenu> sysMenuList = sysMenuService.getMenuListByRoelId(roleId);
        if (CollUtil.isNotEmpty(sysMenuList)) {
            List<String> menuIdList = sysMenuList.stream().map(SysMenu::getMenuId).toList();
            return ResponseResult.success(menuIdList);
        }
        return ResponseResult.success();
    }

    /**
     * 加载对应租户套餐菜单列表树
     *
     * @param packageId 租户套餐ID
     */
    @GetMapping(value = "/tenantPackageMenuTreeselect/{packageId}")
    public ResponseResult<List<String>> tenantPackageMenuTreeSelect(@PathVariable("packageId") String packageId) {
        return ResponseResult.success(sysMenuService.selectMenuListByPackageId(packageId));
    }

    @Operation(summary = "获取菜单表格")
    @GetMapping("menuTable")
    public ResponseResult<List<SysMenu>> menuTable(@LoginUser SysUser sysUser,
                                                   @RequestParam(required = false) String menuName,
                                                   String parentId) {
        List<SysMenu> menuList = sysMenuService.selectMenuList(sysUser, menuName);
        return ResponseResult.success(recursiveMenu(menuList, parentId));
    }


    @Operation(summary = "根据菜单ID获取菜单信息")
    @GetMapping("menuDetailByMenuId/{menuId}")
    public ResponseResult<SysMenu> menuDetailByMenuId(@PathVariable String menuId) {
        return ResponseResult.success(sysMenuService.getById(menuId));
    }

    private List<SysMenu> recursiveMenu(List<SysMenu> allMenuList, String parentId) {
        // 使用 Stream API 进行筛选和遍历
        List<SysMenu> parentMenuList = allMenuList.stream()
                .filter(menu -> menu.getParentId().equals(parentId))
                .sorted((o1, o2) -> (int) (o1.getWeight() - o2.getWeight()))
                .toList();
        getSubList(parentMenuList, allMenuList);
        return parentMenuList;
    }

    private static void getSubList(final List<SysMenu> parentList, final List<SysMenu> all) {
        for (SysMenu sysMenu : parentList) {
            List<SysMenu> subList = all.stream()
                    .filter(o -> o.getParentId()
                            .equals(sysMenu.getMenuId()))
                    .sorted((o1, o2) -> (int) (o1.getWeight() - o2.getWeight())).collect(Collectors.toList());
            sysMenu.setChildren(subList);
            if (!subList.isEmpty()) {
                getSubList(subList, all);
            }
        }
    }


    @Operation(summary = "获取菜单树")
    @GetMapping("menuTree")
    public ResponseResult<List<Tree<String>>> menuTree(@LoginUser SysUser sysUser) {
        List<SysMenu> menuList = sysMenuService.selectMenuList(sysUser, null);
        return ResponseResult.success(getTrees(menuList));
    }



    private static List<Tree<String>> getTrees(List<SysMenu> sysMenuList) {
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setNameKey("label");
        return TreeUtil.build(sysMenuList, "-1", treeNodeConfig, (sysMenu, treeNode) -> {
            treeNode.setWeight(sysMenu.getWeight());
            treeNode.setId(sysMenu.getMenuId());
            treeNode.setParentId(sysMenu.getParentId());
            treeNode.setName(sysMenu.getMenuName());
        });
    }

    @Operation(summary = "保存菜单")
    @PostMapping("save")
    public ResponseResult<Boolean> saveMenu(@RequestBody SysMenu sysMenu) {
        return ResponseResult.success(sysMenuService.save(sysMenu));
    }

    @Operation(summary = "更新菜单")
    @PostMapping("update")
    public ResponseResult<Boolean> updateMenu(@RequestBody SysMenu sysMenu) {
        return ResponseResult.success(sysMenuService.updateById(sysMenu));
    }

    @Operation(summary = "删除菜单")
    @DeleteMapping("delete/{menuId}")
    public ResponseResult<Boolean> deleteMenu(@PathVariable String menuId) {
        // 如果是父级菜单 递归删除子菜单
        List<String> allDeleteMenuIds = new ArrayList<>();
        allDeleteMenuIds.add(menuId);
        // 根据菜单ID获取子菜单
        List<SysMenu> childrenMenuList = sysMenuService.list(new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getParentId, menuId));
        if (CollUtil.isNotEmpty(childrenMenuList)) {
            allDeleteMenuIds.addAll(childrenMenuList.stream().map(SysMenu::getMenuId).toList());
        }
        // 批量删除
        return ResponseResult.success(sysMenuService.removeBatchByIds(allDeleteMenuIds));
    }


}
